4 * Global functions used everywhere
9 * Some globals and requires needed
13 * Total number of articles
14 * @global integer $wgNumberOfArticles
16 $wgNumberOfArticles = -1; # Unset
18 * Total number of views
19 * @global integer $wgTotalViews
23 * Total number of edits
24 * @global integer $wgTotalEdits
29 require_once( 'DatabaseFunctions.php' );
30 require_once( 'UpdateClasses.php' );
31 require_once( 'LogPage.php' );
32 require_once( 'normal/UtfNormalUtil.php' );
35 * Compatibility functions
36 * PHP <4.3.x is not actively supported; 4.1.x and 4.2.x might or might not work.
37 * <4.1.x will not work, as we use a number of features introduced in 4.1.0
38 * such as the new autoglobals.
40 if( !function_exists('iconv') ) {
41 # iconv support is not in the default configuration and so may not be present.
42 # Assume will only ever use utf-8 and iso-8859-1.
43 # This will *not* work in all circumstances.
44 function iconv( $from, $to, $string ) {
45 if(strcasecmp( $from, $to ) == 0) return $string;
46 if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
47 if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
52 if( !function_exists('file_get_contents') ) {
53 # Exists in PHP 4.3.0+
54 function file_get_contents( $filename ) {
55 return implode( '', file( $filename ) );
59 if( !function_exists('is_a') ) {
60 # Exists in PHP 4.2.0+
61 function is_a( $object, $class_name ) {
63 (strcasecmp( get_class( $object ), $class_name ) == 0) ||
64 is_subclass_of( $object, $class_name );
68 # UTF-8 substr function based on a PHP manual comment
69 if ( !function_exists( 'mb_substr' ) ) {
70 function mb_substr( $str, $start ) {
71 preg_match_all( '/./us', $str, $ar );
73 if( func_num_args() >= 3 ) {
74 $end = func_get_arg( 2 );
75 return join( '', array_slice( $ar[0], $start, $end ) );
77 return join( '', array_slice( $ar[0], $start ) );
82 if( !function_exists( 'floatval' ) ) {
84 * First defined in PHP 4.2.0
88 function floatval( $var ) {
94 * Where as we got a random seed
95 * @var bool $wgTotalViews
97 $wgRandomSeeded = false;
100 * Seed Mersenne Twister
101 * Only necessary in PHP < 4.2.0
105 function wfSeedRandom() {
106 global $wgRandomSeeded;
108 if ( ! $wgRandomSeeded && version_compare( phpversion(), '4.2.0' ) < 0 ) {
109 $seed = hexdec(substr(md5(microtime()),-8)) & 0x7fffffff;
111 $wgRandomSeeded = true;
116 * Get a random decimal value between 0 and 1, in a way
117 * not likely to give duplicate values for any realistic
118 * number of articles.
122 function wfRandom() {
123 # The maximum random value is "only" 2^31-1, so get two random
124 # values to reduce the chance of dupes
125 $max = mt_getrandmax();
126 $rand = number_format( (mt_rand() * $max +
mt_rand())
127 / $max / $max, 12, '.', '' );
132 * We want / and : to be included as literal characters in our title URLs.
133 * %2F in the page titles seems to fatally break for some reason.
138 function wfUrlencode ( $s ) {
139 $s = urlencode( $s );
140 $s = preg_replace( '/%3[Aa]/', ':', $s );
141 $s = preg_replace( '/%2[Ff]/', '/', $s );
147 * Sends a line to the debug log if enabled or, optionally, to a comment in output.
148 * In normal operation this is a NOP.
150 * Controlling globals:
151 * $wgDebugLogFile - points to the log file
152 * $wgProfileOnly - if set, normal debug messages will not be recorded.
153 * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
154 * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
156 * @param string $text
157 * @param bool $logonly Set true to avoid appearing in HTML when $wgDebugComments is set
159 function wfDebug( $text, $logonly = false ) {
160 global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
162 # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
163 if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
167 if ( isset( $wgOut ) && $wgDebugComments && !$logonly ) {
168 $wgOut->debug( $text );
170 if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
171 # Strip unprintables; they can switch terminal modes when binary data
172 # gets dumped, which is pretty annoying.
173 $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
174 @error_log
( $text, 3, $wgDebugLogFile );
179 * Log for database errors
180 * @param string $text Database error message.
182 function wfLogDBError( $text ) {
183 global $wgDBerrorLog;
184 if ( $wgDBerrorLog ) {
185 $text = date('D M j G:i:s T Y') . "\t".$text;
186 error_log( $text, 3, $wgDBerrorLog );
193 function logProfilingData() {
194 global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
195 global $wgProfiling, $wgProfileStack, $wgProfileLimit, $wgUser;
198 list( $usec, $sec ) = explode( ' ', $wgRequestTime );
199 $start = (float)$sec +
(float)$usec;
200 $elapsed = $now - $start;
201 if ( $wgProfiling ) {
202 $prof = wfGetProfilingOutput( $start, $elapsed );
204 if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
205 $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
206 if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
207 $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
208 if( !empty( $_SERVER['HTTP_FROM'] ) )
209 $forward .= ' from ' . $_SERVER['HTTP_FROM'];
211 $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
212 if( $wgUser->isAnon() )
214 $log = sprintf( "%s\t%04.3f\t%s\n",
215 gmdate( 'YmdHis' ), $elapsed,
216 urldecode( $_SERVER['REQUEST_URI'] . $forward ) );
217 if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' ||
$wgDebugRawPage ) ) {
218 error_log( $log . $prof, 3, $wgDebugLogFile );
224 * Check if the wiki read-only lock file is present. This can be used to lock
225 * off editing functions, but doesn't guarantee that the database will not be
229 function wfReadOnly() {
230 global $wgReadOnlyFile, $wgReadOnly;
235 if ( '' == $wgReadOnlyFile ) {
239 // Set $wgReadOnly and unset $wgReadOnlyFile, for faster access next time
240 if ( is_file( $wgReadOnlyFile ) ) {
245 $wgReadOnlyFile = '';
251 * Get a message from anywhere, for the current user language
255 function wfMsg( $key ) {
256 $args = func_get_args();
257 array_shift( $args );
258 return wfMsgReal( $key, $args, true );
262 * Get a message from anywhere, for the current global language
264 function wfMsgForContent( $key ) {
265 global $wgForceUIMsgAsContentMsg;
266 $args = func_get_args();
267 array_shift( $args );
269 if( is_array( $wgForceUIMsgAsContentMsg ) &&
270 in_array( $key, $wgForceUIMsgAsContentMsg ) )
272 return wfMsgReal( $key, $args, true, $forcontent );
276 * Get a message from the language file, for the UI elements
278 function wfMsgNoDB( $key ) {
279 $args = func_get_args();
280 array_shift( $args );
281 return wfMsgReal( $key, $args, false );
285 * Get a message from the language file, for the content
287 function wfMsgNoDBForContent( $key ) {
288 global $wgForceUIMsgAsContentMsg;
289 $args = func_get_args();
290 array_shift( $args );
292 if( is_array( $wgForceUIMsgAsContentMsg ) &&
293 in_array( $key, $wgForceUIMsgAsContentMsg ) )
295 return wfMsgReal( $key, $args, false, $forcontent );
300 * Really get a message
302 function wfMsgReal( $key, $args, $useDB, $forContent=false ) {
303 $fname = 'wfMsgReal';
304 wfProfileIn( $fname );
306 $message = wfMsgGetKey( $key, $useDB, $forContent );
307 $message = wfMsgReplaceArgs( $message, $args );
308 wfProfileOut( $fname );
313 * Fetch a message string value, but don't replace any keys yet.
316 * @param bool $forContent
320 function wfMsgGetKey( $key, $useDB, $forContent = false ) {
321 global $wgParser, $wgMsgParserOptions;
322 global $wgContLang, $wgLanguageCode;
323 global $wgMessageCache, $wgLang;
325 if( is_object( $wgMessageCache ) ) {
326 $message = $wgMessageCache->get( $key, $useDB, $forContent );
329 $lang = &$wgContLang;
334 wfSuppressWarnings();
336 if( is_object( $lang ) ) {
337 $message = $lang->getMessage( $key );
343 $message = Language
::getMessage($key);
344 if(strstr($message, '{{' ) !== false) {
345 $message = $wgParser->transformMsg($message, $wgMsgParserOptions);
352 * Replace message parameter keys on the given formatted output.
354 * @param string $message
359 function wfMsgReplaceArgs( $message, $args ) {
360 static $replacementKeys = array( '$1', '$2', '$3', '$4', '$5', '$6', '$7', '$8', '$9' );
362 # Fix windows line-endings
363 # Some messages are split with explode("\n", $msg)
364 $message = str_replace( "\r", '', $message );
367 if( count( $args ) ) {
368 $message = str_replace( $replacementKeys, $args, $message );
374 * Return an HTML-escaped version of a message.
375 * Parameter replacements, if any, are done *after* the HTML-escaping,
376 * so parameters may contain HTML (eg links or form controls). Be sure
377 * to pre-escape them if you really do want plaintext, or just wrap
378 * the whole thing in htmlspecialchars().
381 * @param string ... parameters
384 function wfMsgHtml( $key ) {
385 $args = func_get_args();
386 array_shift( $args );
387 return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
391 * Just like exit() but makes a note of it.
392 * Commits open transactions except if the error parameter is set
394 function wfAbruptExit( $error = false ){
395 global $wgLoadBalancer;
396 static $called = false;
402 if( function_exists( 'debug_backtrace' ) ){ // PHP >= 4.3
403 $bt = debug_backtrace();
404 for($i = 0; $i < count($bt) ; $i++
){
405 $file = $bt[$i]['file'];
406 $line = $bt[$i]['line'];
407 wfDebug("WARNING: Abrupt exit in $file at line $line\n");
410 wfDebug('WARNING: Abrupt exit\n');
413 $wgLoadBalancer->closeAll();
421 function wfErrorExit() {
422 wfAbruptExit( true );
426 * Die with a backtrace
427 * This is meant as a debugging aid to track down where bad data comes from.
428 * Shouldn't be used in production code except maybe in "shouldn't happen" areas.
430 * @param string $msg Message shown when dieing.
432 function wfDebugDieBacktrace( $msg = '' ) {
433 global $wgCommandLineMode;
435 $backtrace = wfBacktrace();
436 if ( $backtrace !== false ) {
437 if ( $wgCommandLineMode ) {
438 $msg .= "\nBacktrace:\n$backtrace";
440 $msg .= "\n<p>Backtrace:</p>\n$backtrace";
447 function wfBacktrace() {
448 global $wgCommandLineMode;
449 if ( !function_exists( 'debug_backtrace' ) ) {
453 if ( $wgCommandLineMode ) {
458 $backtrace = debug_backtrace();
459 foreach( $backtrace as $call ) {
460 if( isset( $call['file'] ) ) {
461 $f = explode( DIRECTORY_SEPARATOR
, $call['file'] );
462 $file = $f[count($f)-1];
466 if( isset( $call['line'] ) ) {
467 $line = $call['line'];
471 if ( $wgCommandLineMode ) {
472 $msg .= "$file line $line calls ";
474 $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
476 if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
477 $msg .= $call['function'] . '()';
479 if ( $wgCommandLineMode ) {
485 if ( $wgCommandLineMode ) {
495 /* Some generic result counters, pulled out of SearchEngine */
501 function wfShowingResults( $offset, $limit ) {
503 return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ) );
509 function wfShowingResultsNum( $offset, $limit, $num ) {
511 return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+
1 ), $wgLang->formatNum( $num ) );
517 function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
518 global $wgUser, $wgLang;
519 $fmtLimit = $wgLang->formatNum( $limit );
520 $prev = wfMsg( 'prevn', $fmtLimit );
521 $next = wfMsg( 'nextn', $fmtLimit );
523 if( is_object( $link ) ) {
526 $title =& Title
::newFromText( $link );
527 if( is_null( $title ) ) {
532 $sk = $wgUser->getSkin();
533 if ( 0 != $offset ) {
534 $po = $offset - $limit;
535 if ( $po < 0 ) { $po = 0; }
536 $q = "limit={$limit}&offset={$po}";
537 if ( '' != $query ) { $q .= '&'.$query; }
538 $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
539 } else { $plink = $prev; }
541 $no = $offset +
$limit;
542 $q = 'limit='.$limit.'&offset='.$no;
543 if ( '' != $query ) { $q .= '&'.$query; }
548 $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
550 $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
551 wfNumLink( $offset, 50, $title, $query ) . ' | ' .
552 wfNumLink( $offset, 100, $title, $query ) . ' | ' .
553 wfNumLink( $offset, 250, $title, $query ) . ' | ' .
554 wfNumLink( $offset, 500, $title, $query );
556 return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
562 function wfNumLink( $offset, $limit, &$title, $query = '' ) {
563 global $wgUser, $wgLang;
564 if ( '' == $query ) { $q = ''; }
565 else { $q = $query.'&'; }
566 $q .= 'limit='.$limit.'&offset='.$offset;
568 $fmtLimit = $wgLang->formatNum( $limit );
569 $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
575 * @todo FIXME: we may want to blacklist some broken browsers
577 * @return bool Whereas client accept gzip compression
579 function wfClientAcceptsGzip() {
582 # FIXME: we may want to blacklist some broken browsers
584 '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
585 $_SERVER['HTTP_ACCEPT_ENCODING'],
587 if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
588 wfDebug( " accepts gzip\n" );
596 * Yay, more global functions!
598 function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
600 return $wgRequest->getLimitOffset( $deflimit, $optionname );
604 * Escapes the given text so that it may be output using addWikiText()
605 * without any linking, formatting, etc. making its way through. This
606 * is achieved by substituting certain characters with HTML entities.
607 * As required by the callers, <nowiki> is not used. It currently does
608 * not filter out characters which have special meaning only at the
609 * start of a line, such as "*".
611 * @param string $text Text to be escaped
613 function wfEscapeWikiText( $text ) {
615 array( '[', '|', '\'', 'ISBN ' , '://' , "\n=", '{{' ),
616 array( '[', '|', ''', 'ISBN ', '://' , "\n=", '{{' ),
617 htmlspecialchars($text) );
624 function wfQuotedPrintable( $string, $charset = '' ) {
625 # Probably incomplete; see RFC 2045
626 if( empty( $charset ) ) {
627 global $wgInputEncoding;
628 $charset = $wgInputEncoding;
630 $charset = strtoupper( $charset );
631 $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
633 $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
634 $replace = $illegal . '\t ?_';
635 if( !preg_match( "/[$illegal]/", $string ) ) return $string;
636 $out = "=?$charset?Q?";
637 $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
643 * Returns an escaped string suitable for inclusion in a string literal
644 * for JavaScript source code.
645 * Illegal control characters are assumed not to be present.
647 * @param string $string
650 function wfEscapeJsString( $string ) {
651 // See ECMA 262 section 7.8.4 for string literal format
659 # To avoid closing the element or CDATA section
663 return strtr( $string, $pairs );
671 $st = explode( ' ', microtime() );
672 return (float)$st[0] +
(float)$st[1];
676 * Changes the first character to an HTML entity
678 function wfHtmlEscapeFirst( $text ) {
680 $newText = substr($text, 1);
681 return "&#$ord;$newText";
685 * Sets dest to source and returns the original value of dest
686 * If source is NULL, it just returns the value, it doesn't set the variable
688 function wfSetVar( &$dest, $source ) {
690 if ( !is_null( $source ) ) {
697 * As for wfSetVar except setting a bit
699 function wfSetBit( &$dest, $bit, $state = true ) {
700 $temp = (bool)($dest & $bit );
701 if ( !is_null( $state ) ) {
712 * This function takes two arrays as input, and returns a CGI-style string, e.g.
713 * "days=7&limit=100". Options in the first array override options in the second.
714 * Options set to "" will not be output.
716 function wfArrayToCGI( $array1, $array2 = NULL )
718 if ( !is_null( $array2 ) ) {
719 $array1 = $array1 +
$array2;
723 foreach ( $array1 as $key => $value ) {
724 if ( '' !== $value ) {
728 $cgi .= urlencode( $key ) . '=' . urlencode( $value );
735 * This is obsolete, use SquidUpdate::purge()
738 function wfPurgeSquidServers ($urlArr) {
739 SquidUpdate
::purge( $urlArr );
743 * Windows-compatible version of escapeshellarg()
744 * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
745 * function puts single quotes in regardless of OS
747 function wfEscapeShellArg( ) {
748 $args = func_get_args();
751 foreach ( $args as $arg ) {
758 if ( wfIsWindows() ) {
759 $retVal .= '"' . str_replace( '"','\"', $arg ) . '"';
761 $retVal .= escapeshellarg( $arg );
768 * wfMerge attempts to merge differences between three texts.
769 * Returns true for a clean merge and false for failure or a conflict.
771 function wfMerge( $old, $mine, $yours, &$result ){
774 # This check may also protect against code injection in
775 # case of broken installations.
776 if(! file_exists( $wgDiff3 ) ){
780 # Make temporary files
782 $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
783 $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
784 $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
786 fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
787 fwrite( $mytextFile, $mine ); fclose( $mytextFile );
788 fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
790 # Check for a conflict
791 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a --overlap-only ' .
792 wfEscapeShellArg( $mytextName ) . ' ' .
793 wfEscapeShellArg( $oldtextName ) . ' ' .
794 wfEscapeShellArg( $yourtextName );
795 $handle = popen( $cmd, 'r' );
797 if( fgets( $handle, 1024 ) ){
805 $cmd = wfEscapeShellArg( $wgDiff3 ) . ' -a -e --merge ' .
806 wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
807 $handle = popen( $cmd, 'r' );
810 $data = fread( $handle, 8192 );
811 if ( strlen( $data ) == 0 ) {
817 unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
824 function wfVarDump( $var ) {
826 $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
827 if ( headers_sent() ||
!@is_object
( $wgOut ) ) {
830 $wgOut->addHTML( $s );
835 * Provide a simple HTTP error.
837 function wfHttpError( $code, $label, $desc ) {
840 header( "HTTP/1.0 $code $label" );
841 header( "Status: $code $label" );
842 $wgOut->sendCacheControl();
844 header( 'Content-type: text/html' );
845 print "<html><head><title>" .
846 htmlspecialchars( $label ) .
847 "</title></head><body><h1>" .
848 htmlspecialchars( $label ) .
850 htmlspecialchars( $desc ) .
851 "</p></body></html>\n";
855 * Converts an Accept-* header into an array mapping string values to quality
858 function wfAcceptToPrefs( $accept, $def = '*/*' ) {
859 # No arg means accept anything (per HTTP spec)
861 return array( $def => 1 );
866 $parts = explode( ',', $accept );
868 foreach( $parts as $part ) {
869 # FIXME: doesn't deal with params like 'text/html; level=1'
870 @list
( $value, $qpart ) = explode( ';', $part );
871 if( !isset( $qpart ) ) {
873 } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
874 $prefs[$value] = $match[1];
882 * Checks if a given MIME type matches any of the keys in the given
883 * array. Basic wildcards are accepted in the array keys.
885 * Returns the matching MIME type (or wildcard) if a match, otherwise
888 * @param string $type
889 * @param array $avail
893 function mimeTypeMatch( $type, $avail ) {
894 if( array_key_exists($type, $avail) ) {
897 $parts = explode( '/', $type );
898 if( array_key_exists( $parts[0] . '/*', $avail ) ) {
899 return $parts[0] . '/*';
900 } elseif( array_key_exists( '*/*', $avail ) ) {
909 * Returns the 'best' match between a client's requested internet media types
910 * and the server's list of available types. Each list should be an associative
911 * array of type to preference (preference is a float between 0.0 and 1.0).
912 * Wildcards in the types are acceptable.
914 * @param array $cprefs Client's acceptable type list
915 * @param array $sprefs Server's offered types
918 * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
919 * XXX: generalize to negotiate other stuff
921 function wfNegotiateType( $cprefs, $sprefs ) {
924 foreach( array_keys($sprefs) as $type ) {
925 $parts = explode( '/', $type );
926 if( $parts[1] != '*' ) {
927 $ckey = mimeTypeMatch( $type, $cprefs );
929 $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
934 foreach( array_keys( $cprefs ) as $type ) {
935 $parts = explode( '/', $type );
936 if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
937 $skey = mimeTypeMatch( $type, $sprefs );
939 $combine[$type] = $sprefs[$skey] * $cprefs[$type];
947 foreach( array_keys( $combine ) as $type ) {
948 if( $combine[$type] > $bestq ) {
950 $bestq = $combine[$type];
959 * Returns an array where the values in the first array are replaced by the
960 * values in the second array with the corresponding keys
964 function wfArrayLookup( $a, $b ) {
965 return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
969 * Convenience function; returns MediaWiki timestamp for the present time.
972 function wfTimestampNow() {
974 return wfTimestamp( TS_MW
, time() );
978 * Reference-counted warning suppression
980 function wfSuppressWarnings( $end = false ) {
981 static $suppressCount = 0;
982 static $originalLevel = false;
985 if ( $suppressCount ) {
987 if ( !$suppressCount ) {
988 error_reporting( $originalLevel );
992 if ( !$suppressCount ) {
993 $originalLevel = error_reporting( E_ALL
& ~
( E_WARNING | E_NOTICE
) );
1000 * Restore error level to previous value
1002 function wfRestoreWarnings() {
1003 wfSuppressWarnings( true );
1006 # Autodetect, convert and provide timestamps of various types
1009 * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
1011 define('TS_UNIX', 0);
1014 * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
1019 * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
1024 * RFC 2822 format, for E-mail and HTTP headers
1026 define('TS_RFC2822', 3);
1029 * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
1031 * @link http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
1032 * DateTime tag and page 36 for the DateTimeOriginal and
1033 * DateTimeDigitized tags.
1035 define('TS_EXIF', 4);
1039 * @param mixed $outputtype A timestamp in one of the supported formats, the
1040 * function will autodetect which format is supplied
1041 and act accordingly.
1042 * @return string Time in the format specified in $outputtype
1044 function wfTimestamp($outputtype=TS_UNIX
,$ts=0) {
1047 } elseif (preg_match("/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1049 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1050 (int)$da[2],(int)$da[3],(int)$da[1]);
1051 } elseif (preg_match("/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/",$ts,$da)) {
1053 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1054 (int)$da[2],(int)$da[3],(int)$da[1]);
1055 } elseif (preg_match("/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/",$ts,$da)) {
1057 $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
1058 (int)$da[2],(int)$da[3],(int)$da[1]);
1059 } elseif (preg_match("/^(\d{1,13})$/",$ts,$datearray)) {
1063 # Bogus value; fall back to the epoch...
1064 wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
1069 switch($outputtype) {
1073 return gmdate( 'YmdHis', $uts );
1075 return gmdate( 'Y-m-d H:i:s', $uts );
1076 // This shouldn't ever be used, but is included for completeness
1078 return gmdate( 'Y:m:d H:i:s', $uts );
1080 return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
1082 wfDebugDieBacktrace( 'wfTimestamp() called with illegal output type.');
1087 * Return a formatted timestamp, or null if input is null.
1088 * For dealing with nullable timestamp columns in the database.
1089 * @param int $outputtype
1093 function wfTimestampOrNull( $outputtype = TS_UNIX
, $ts = null ) {
1094 if( is_null( $ts ) ) {
1097 return wfTimestamp( $outputtype, $ts );
1102 * Check where as the operating system is Windows
1104 * @return bool True if it's windows, False otherwise.
1106 function wfIsWindows() {
1107 if (substr(php_uname(), 0, 7) == 'Windows') {
1115 * Swap two variables
1117 function swap( &$x, &$y ) {
1123 function wfGetSiteNotice() {
1124 global $wgSiteNotice, $wgTitle, $wgOut;
1125 $fname = 'wfGetSiteNotice';
1126 wfProfileIn( $fname );
1128 $notice = wfMsg( 'sitenotice' );
1129 if( $notice == '<sitenotice>' ||
$notice == '-' ) {
1132 if( $notice == '' ) {
1133 # We may also need to override a message with eg downtime info
1134 # FIXME: make this work!
1135 $notice = $wgSiteNotice;
1137 if($notice != '-' && $notice != '') {
1138 $specialparser = new Parser();
1139 $parserOutput = $specialparser->parse( $notice, $wgTitle, $wgOut->mParserOptions
, false );
1140 $notice = $parserOutput->getText();
1142 wfProfileOut( $fname );
1147 * Format an XML element with given attributes and, optionally, text content.
1148 * Element and attribute names are assumed to be ready for literal inclusion.
1149 * Strings are assumed to not contain XML-illegal characters; special
1150 * characters (<, >, &) are escaped but illegals are not touched.
1152 * @param string $element
1153 * @param array $attribs Name=>value pairs. Values will be escaped.
1154 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1157 function wfElement( $element, $attribs = null, $contents = '') {
1158 $out = '<' . $element;
1159 if( !is_null( $attribs ) ) {
1160 foreach( $attribs as $name => $val ) {
1161 $out .= ' ' . $name . '="' . htmlspecialchars( $val ) . '"';
1164 if( is_null( $contents ) ) {
1167 if( $contents == '' ) {
1171 $out .= htmlspecialchars( $contents );
1172 $out .= "</$element>";
1179 * Format an XML element as with wfElement(), but run text through the
1180 * UtfNormal::cleanUp() validator first to ensure that no invalid UTF-8
1183 * @param string $element
1184 * @param array $attribs Name=>value pairs. Values will be escaped.
1185 * @param bool $contents NULL to make an open tag only; '' for a contentless closed tag (default)
1188 function wfElementClean( $element, $attribs = array(), $contents = '') {
1190 $attribs = array_map( array( 'UtfNormal', 'cleanUp' ), $attribs );
1193 $contents = UtfNormal
::cleanUp( $contents );
1195 return wfElement( $element, $attribs, $contents );
1198 /** Global singleton instance of MimeMagic. This is initialized on demand,
1199 * please always use the wfGetMimeMagic() function to get the instance.
1205 /** Factory functions for the global MimeMagic object.
1206 * This function always returns the same singleton instance of MimeMagic.
1207 * That objects will be instantiated on the first call to this function.
1208 * If needed, the MimeMagic.php file is automatically included by this function.
1209 * @return MimeMagic the global MimeMagic objects.
1211 function &wfGetMimeMagic() {
1212 global $wgMimeMagic;
1214 if (!is_null($wgMimeMagic)) {
1215 return $wgMimeMagic;
1218 if (!class_exists("MimeMagic")) {
1220 require_once("MimeMagic.php");
1223 $wgMimeMagic= new MimeMagic();
1225 return $wgMimeMagic;
1230 * Tries to get the system directory for temporary files.
1231 * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
1232 * and if none are set /tmp is returned as the generic Unix default.
1234 * NOTE: When possible, use the tempfile() function to create temporary
1235 * files to avoid race conditions on file creation, etc.
1239 function wfTempDir() {
1240 foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
1241 $tmp = getenv( $var );
1242 if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
1246 # Hope this is Unix of some kind!
1251 * Make directory, and make all parent directories if they don't exist
1253 function wfMkdirParents( $fullDir, $mode ) {
1254 $parts = explode( '/', $fullDir );
1257 foreach ( $parts as $dir ) {
1258 $path .= $dir . '/';
1259 if ( !is_dir( $path ) ) {
1260 if ( !mkdir( $path, $mode ) ) {
1269 * Increment a statistics counter
1271 function wfIncrStats( $key ) {
1272 global $wgDBname, $wgMemc;
1273 $key = "$wgDBname:stats:$key";
1274 if ( is_null( $wgMemc->incr( $key ) ) ) {
1275 $wgMemc->add( $key, 1 );
1280 * @param mixed $nr The number to format
1281 * @param int $acc The number of digits after the decimal point, default 2
1282 * @param bool $round Whether or not to round the value, default true
1285 function wfPercent( $nr, $acc = 2, $round = true ) {
1286 $ret = sprintf( "%.${acc}f", $nr );
1287 return $round ?
round( $ret, $acc ) . '%' : "$ret%";
1291 * Encrypt a username/password.
1293 * @param string $userid ID of the user
1294 * @param string $password Password of the user
1295 * @return string Hashed password
1297 function wfEncryptPassword( $userid, $password ) {
1298 global $wgPasswordSalt;
1299 $p = md5( $password);
1302 return md5( "{$userid}-{$p}" );